export class AcGame {
    constructor(id, AcWingOs) {
        this.id = id;
        this.$ac_game = $('#' + id);
        this.AcWingOs = AcWingOs;
        this.settings = new Settings(this);
        this.menu = new AcGameMenu(this);
        this.playground = new AcGamePlayground(this);

        // 初始化背景音乐
        this.backgroundMusic = new Audio('/static/sounds/backgroundmusic.mp3');
        if (this.backgroundMusic) {
            this.backgroundMusic.loop = true; // 循环播放
        }
        this.musicPlaying = false;

        this.start();
    }

    start() {
    }

    // 播放背景音乐（通过按钮调用）
    playBackgroundMusic() {
        if (this.backgroundMusic && !this.musicPlaying) {
            // 先静音再播放以绕过浏览器限制
            this.backgroundMusic.muted = true;
            const playPromise = this.backgroundMusic.play();

            if (playPromise !== undefined) {
                playPromise
                    .then(() => {
                        // 播放成功后再取消静音
                        this.backgroundMusic.muted = false;
                        this.musicPlaying = true;
                    })
            }
        }
    }

    // 停止背景音乐
    stopBackgroundMusic() {
        if (this.backgroundMusic) {
            this.backgroundMusic.pause();
            this.backgroundMusic.currentTime = 0;
        }
        this.musicPlaying = false;
    }

    // 切换音乐播放状态
    toggleMusic() {
        if (this.musicPlaying) {
            this.stopBackgroundMusic();
            this.musicPlaying = false;
        } else {
            this.playBackgroundMusic();
            this.musicPlaying = true;
        }
        return this.musicPlaying;
    }
}
